package core;

import java.util.List;
import java.util.ArrayList;
import core.Card;

public final class Poker {

	private List<Card> cards = new ArrayList<Card>();
	public final static int intcardscut = 13*4;
	
	public Poker(){
		for(int i=1; i<=13; i++){
			this.cards.add(new Card(Card.DIAMONDS, i));
			this.cards.add(new Card(Card.CLUBS, i));
			this.cards.add(new Card(Card.HEARTS, i));
			this.cards.add(new Card(Card.SPADES, i));
		}
	}

	public Card getCards(int index){
		return this.cards.get(index);
	}

	public void shuffle(){

		List<Card> mapresult = new ArrayList<Card>();
		Card onecard = null;
		int key;
		
		for(int i=1; i<=Poker.intcardscut; i++){
			key = (int)Math.round(Math.random()*(Poker.intcardscut-i));
			onecard = this.cards.get(key);
			mapresult.add(onecard);
			this.cards.remove(key);
		}
		this.cards = mapresult;
	}

	public void sort(){
		List<Card> lstdiamonds = new ArrayList<Card>();
		List<Card> lstclubs = new ArrayList<Card>();
		List<Card> lsthearts = new ArrayList<Card>();
		List<Card> lstspades = new ArrayList<Card>();
		
		for(Card tmpcard : this.cards){
			switch(tmpcard.getkind()){
				case Card.DIAMONDS : lstdiamonds.add(tmpcard);break;
				case Card.CLUBS : lstclubs.add(tmpcard);break;
				case Card.HEARTS : lsthearts.add(tmpcard);break;
				case Card.SPADES : lstspades.add(tmpcard);break;
			}
		}
		this.cards = new ArrayList<Card>();
		this.cards.addAll(this.basesort(lstdiamonds));
		this.cards.addAll(this.basesort(lstclubs));
		this.cards.addAll(this.basesort(lsthearts));
		this.cards.addAll(this.basesort(lstspades));

	}
	
	private List<Card> basesort(List<Card> insertlist){

		for(int i=0; i<insertlist.size()-1; i++){
			for(int j=i+1; j<insertlist.size(); j++){
				if(insertlist.get(i).getnumber()>insertlist.get(j).getnumber()){
					Card tmpcard = insertlist.get(i);
					insertlist.remove(i);
					insertlist.add(i, insertlist.get(j-1));
					insertlist.remove(j);
					insertlist.add(j, tmpcard);
				}
			}
		}
		return insertlist;
	}
	
	public String toString(){
		StringBuffer sbresult = new StringBuffer();
		for(int i=0; i<13*4; i++){
			sbresult.append(cards.get(i));
			sbresult.append("|");
		}
		return sbresult.toString();
	}
}
